how to write json to file in php

63

$data = array(
    'image' => $image_url,
    'mood' => $image_mood,
    'date' => $image_date
);

$data_array = file_get_contents($file_path);
$data_element = json_decode($data_array, true);
$data_element[] = $data;
$new_data = json_encode($data_element, JSON_PRETTY_PRINT);

if (!file_put_contents($file_path, $new_data)) {
    echo "success";
} else {
    echo "fail";
}
<?php
  header('Content-type: application/json');
  echo json_encode( explode("\r\n",file_get_contents('data.txt')) );
?>

Comments

Submit
0 Comments